#include "stdafx.h"
#include "Logging.h"
#include "Routines.h"

Logging& Logging::Logger(const String& aFile)
{
    static Logging* Item = 0;

    if (Item == 0) {
        String FullPath;
        if (aFile == "") {
            _TCHAR Buffer[MAX_PATH + 1] = {0};
            GetTempPath(MAX_PATH, Buffer);
            SYSTEMTIME DateTime;
            GetLocalTime(&DateTime);

            for (DWORD Index = 1; Index < 999; ++Index) {
                String Name = (boost::format("%d-%02d-%02d %02d %02d %03d.imsi.log")
                    % DateTime.wYear
                    % DateTime.wMonth
                    % DateTime.wDay
                    % DateTime.wHour
                    % DateTime.wMinute
                    % Index).str();
                Name = PathAppend(Buffer, Name);
                if (!FileExists(Name)) {
                    FullPath = Name;
                    break;
                }
            }
            if (FullPath.size() == 0) {
                throw std::runtime_error("unable to create log file name");
            }
        }
        else {
            FullPath = aFile;
        }

        Item = new Logging(FullPath);
    }

    return *Item;
}

Logging::Logging(const String& aFile)
: mFile(aFile), mOutput(0)
{
    //ctor
}

Logging::~Logging()
{
    CloseHandle(mOutput);
}

void Logging::Write(const String& aText)
{
    ConditionalOpenHandle();
    SYSTEMTIME DateTime;
    GetLocalTime(&DateTime);
    String Output = (boost::format("%02d:%02d:%02d - %s\n")
                     % DateTime.wHour
                     % DateTime.wMinute
                     % DateTime.wSecond
                     % aText.c_str()).str();
    DWORD Dummy;
    WriteFile(mOutput, Output.c_str(), Output.size(), &Dummy, 0);
    FlushFileBuffers(mOutput);
}

void Logging::ConditionalOpenHandle()
{
    if (mOutput == 0) {
        mOutput = CreateFile(mFile.c_str(), GENERIC_WRITE, FILE_SHARE_READ, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
    }
}
